<template>
    <div>
      <el-breadcrumb   separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-dialog title="添加角色"
                 :visible.sync="addRolesDialogVisible"
                 width="50%"
                 @close="addRolesClosed">
        <el-form label-width="80px"
                  :model='addRolesForm'
                  :rules="rolesFormRules"
                  ref="addRolesFormRef">
          <el-form-item label="角色名称" prop="roleName"><el-input v-model="addRolesForm.roleName"></el-input></el-form-item>
          <el-form-item label="角色描述" prop="roleDesc"><el-input v-model="addRolesForm.roleDesc"></el-input></el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRoles">确定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑用户属性"
                 :visible.sync="editRoleDialogVisible"
                 width="50%">
        <el-form label-width="65px"
                  :model="editRoleForm"
                  :rules="rolesFormRules"
                  ref="editRoleFormRef">
          <el-form-item label="角色名称" prop="roleName"><el-input v-model="editRoleForm.roleName"></el-input></el-form-item>
          <el-form-item label="角色描述" prop="roleDesc"><el-input v-model="editRoleForm.roleDesc"></el-input></el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editRole">确定</el-button>
        </span>
      </el-dialog>
      <el-table :data="roleList"
                border
                stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? '':'bdtop', 'vertical-center']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag closable @close="removeRightById">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '':'bdtop', 'vertical-center']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" align="center" label="No."></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditRoleDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoleById(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="分配权限"
                 :visible.sync="showSetRightDialogVisible"
                 width="50%"
                 @close="setSetRightDialogClosed">
        <el-tree :data="rigthsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showSetRightDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="allotRights">确定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '角色名称长度在2~8个字符之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 15, message: '角色描述长度在1~15个字符之间', trigger: 'blur' }
        ]
      },
      addRolesDialogVisible: false,
      editRoleDialogVisible: false,
      editRoleForm: {},
      showSetRightDialogVisible: false,
      rigthsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!')
      }
      this.roleList = res.data
    },
    addRoles () {
      this.$refs.addRolesFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles/', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色列表失败!')
        }
        this.addRolesDialogVisible = false
        this.getRolesList()
        this.$message.success('添加角色成功!')
      })
    },
    addRolesClosed () {
      this.$refs.addRolesFormRef.resetFields()
    },
    async removeRightById () {
      const confirmResult = await this.$confirm('此操作将永久删除该角色，要继续吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
    },
    async deleteRoleById (id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该角色！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除用户成功')
      this.getRolesList()
    },
    async showEditRoleDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    editRole () {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, { roleName: this.editRoleForm.roleName, roleDesc: this.editRoleForm.roleDesc })
        console.log(this.editRoleForm.roleId, res.data, res.meta)
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色信息失败')
        }
        this.editRoleDialogVisible = false
        this.getRolesList()
        this.$message.success('更新角色信息成功')
      })
    },
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败!')
      }
      this.rigthsList = res.data
      this.getLeafKeys(role, this.defKeys)
      this.showSetRightDialogVisible = true
      this.$message.success('获取权限信息成功')
    },
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)// 如果当前node节点不包含children属性，则是三级节点
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr))
    },
    setSetRightDialogClosed () {
      this.defKeys = []
    },
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.showSetRightDialogVisible = false
    }
  }
}
</script>

<style>
.bdtop {
  border-top: 1px solid #eee
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vertical-center {
  display: flex;
  align-items: center;
}

.el-tag {
  margin: 7px;
}
</style>
